/**
 * created by 小卷毛, 2021-07-14
 * Copyright (c) 2021, 416143467@qq.com All Rights Reserved.
 * #                   *********                            #
 * #                  ************                          #
 * #                  *************                         #
 * #                 **  ***********                        #
 * #                ***  ****** *****                       #
 * #                *** *******   ****                      #
 * #               ***  ********** ****                     #
 * #              ****  *********** ****                    #
 * #            *****   ***********  *****                  #
 * #           ******   *** ********   *****                #
 * #           *****   ***   ********   ******              #
 * #          ******   ***  ***********   ******            #
 * #         ******   **** **************  ******           #
 * #        *******  ********************* *******          #
 * #        *******  ******************************         #
 * #       *******  ****** ***************** *******        #
 * #       *******  ****** ****** *********   ******        #
 * #       *******    **  ******   ******     ******        #
 * #       *******        ******    *****     *****         #
 * #        ******        *****     *****     ****          #
 * #         *****        ****      *****     ***           #
 * #          *****       ***        ***      *             #
 * #            **       ****        ****                   #
 */
package com.rzico.sbl.viewmodel

import com.google.android.material.tabs.TabLayout
import com.lzg.extend.BaseResponse
import com.lzg.extend.jackson.JacksonConvert
import com.lzg.okrx.RxSingleHelper
import com.lzg.okrx.adapter.FlowableBody
import com.lzy.okgo.OkGo
import com.rzico.sbl.R
import com.rzico.sbl.model.OrderFooter
import com.rzico.sbl.model.OrderHeader
import com.rzico.sbl.model.OrderModel
import com.rzico.sbl.ui.report.other.ReportUrl
import com.xinnuo.common.extend.condition
import com.xinnuo.common.extend.find
import com.xinnuo.common.helper.getTimeString
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.utils.applyFlowableSchedulers
import com.xinnuo.common_ui.utils.applySchedulers
import com.xinnuo.common_ui.utils.subscribeByFinally
import com.xinnuo.common_ui.view.BadgeTextView

/**
 * 描 述：报货运单操作相关
 * 作 者：小卷毛  2021-07-14 15:05
 * 修改描述：
 * 修 改 人：
 * 修改版本：
 */
class ReportDeliverViewModel : CommonViewModel() {

    /**
     * 获取运单列表
     */
    fun deliverList(
        page: Int,
        state: String,
        keyWord: String,
        onSuccess: (ArrayList<Any>) -> Unit = {},
        onFinally: () -> Unit = {}
    ) = mDisposables.add(
        OkGo.post<BaseResponse<OrderModel>>(ReportUrl.getBaseUrl().rptDeliver)
            .isMultipart(true)
            .params(
                getParams(
                    "status" to state,
                    "searchValue" to keyWord,
                    "pageStart" to page * 10,
                    "pageSize" to 10
                )
            )
            .converter(object : JacksonConvert<BaseResponse<OrderModel>>() {})
            .adapt(FlowableBody())
            .compose(applyFlowableSchedulers())
            .map {
                ArrayList<Any>().apply {
                    it.data.data.forEachIndexed { index, item ->
                        // 添加Header
                        add(OrderHeader().apply {
                            position = index
                            orderSN = item.orderSn
                            shippingSn = item.sn
                            status_hint = item.statusDescr
                            hint = "下单时间: "
                            time = item.createDate.getTimeString()
                        })

                        // 添加商品
                        addItems(
                            item.shippingItems.onEach {
                                it.orderSN = item.orderSn
                                it.shippingSn = item.sn
                                it.position = index
                                it.methodDescr = item.methodDescr.orEmpty()
                            }
                        )

                        // 添加Footer
                        add(OrderFooter().apply {
                            id = item.id
                            position = index
                            orderId = item.orderId.orEmpty()
                            orderSN = item.orderSn
                            shippingSn = item.sn
                            status = item.status.orEmpty()
                            total_num = item.quantity
                            name = item.consignee.orEmpty()
                            phone = item.phone.orEmpty()
                            address = item.address
                            adminName = item.adminName.orEmpty()
                            adminPhone = item.adminPhone.orEmpty()
                            methodDescr = item.methodDescr.orEmpty()
                            printStatus = item.printStatus.orEmpty()

                            (status == "dispatch")
                                .condition {
                                    hint_btn1 = "送达"
                                    hint_btn2 = when (printStatus) {
                                        "confirmed", "printed" -> ""
                                        else -> "打单"
                                    }
                                    hint_btn3 = "撤消"
                                }
                        })
                    }
                }
            }
            .subscribeByFinally(
                event = this,
                onSuccess = onSuccess,
                onFinally = onFinally
            )
    )

    /**
     * 运单数量
     */
    fun orderCount() =
        RxSingleHelper
            .requestString(
                url = ReportUrl.getBaseUrl().reportSCut,
            )
            .compose(applySchedulers())
            .doOnSubscribe { }
            .doFinally { }

    /**
     * 订单详情
     */
    fun orderDetail(orderSN: String) =
        RxSingleHelper.requestString(
            url = ReportUrl.getBaseUrl().reportDet,
            params = getParams("sn" to orderSN)
        )
            .compose(applySchedulers())
            .doOnSubscribe { showLoading() }
            .doFinally { dismissLoading() }

    /**
     * 打印订单 BaseUrl.reportPrt
     */
    fun operateDeliver(url: String, orderSN: String) =
        RxSingleHelper.requestString(
            url = url,
            params = getParams("sn" to orderSN)
        )
            .compose(applySchedulers())
            .doOnSubscribe { showLoading() }
            .doFinally { dismissLoading() }

    /**
     * 更新自定义Tab数量
     */
    fun updateNum(
        unconfirmed: String,
        confirmed: String,
        completed: String,
        layout: TabLayout
    ) {
        layout.getTabAt(0)?.let { tab ->
            tab.customView
                ?.find<BadgeTextView>(R.id.item_tab_num)
                ?.setBadgeCount(unconfirmed)
        }
        layout.getTabAt(1)?.let { tab ->
            tab.customView
                ?.find<BadgeTextView>(R.id.item_tab_num)
                ?.setBadgeCount(confirmed)
        }
        layout.getTabAt(2)?.let { tab ->
            tab.customView
                ?.find<BadgeTextView>(R.id.item_tab_num)
                ?.setBadgeCount(completed)
        }
    }

}